<?php

// **************************************************************
// | Name: 星空框架  用户相关服务
// **************************************************************
// | Version: V5.0
// **************************************************************
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// **************************************************************
// | City: 青岛
// **************************************************************
// | Time: 2021-09-15 09:20
// **************************************************************
declare(strict_types=1);

namespace app\common\services;

use app\common\model\User as UserModel;
use app\common\model\Member as MemberModel; // 旧平台会员数据
use app\common\model\UserAchievement as UserAchievementModel; // 业绩统计
use app\common\model\UserLevel as UserLevelModel; // 会员等级
use app\common\model\UserUpLog as UserUpLogModel; // 会员升级记录
use app\common\model\BackMoney as BackMoneyModel; // 会员返利记录
use app\common\model\Order as OrderModel;
use app\common\model\SubOrder as SubOrderModel;
use app\common\model\GoodsOrder as GoodsOrderModel;
use app\common\model\RefundOrder as RefundOrderModel;
use app\common\model\AvgUser as AvgUserModel;
use app\common\model\BonusUser as BonusUserModel;
use app\common\model\AvgBackMoney as AvgBackMoneyModel;
use app\common\model\BonusRule as BonusRuleModel;
use app\common\model\MoneyChanage as MoneyChanageModel;
use app\common\model\Withdrawal as WithDrawalModel;
use app\common\services\OrderServices;
use app\common\services\FinanceServices;
use app\common\services\SendMsg;
use app\common\services\Task;
use think\facade\Db;

/**
 * @xk 用户相关服务
 */
class UserServices
{
    /**
     * @xk 绑定上级会员
     *
     * @method syncUserBind
     * @param  [type]       $l_user_sn                 [description]
     * @param  boolean      $ifshare                   [description]
     * @return [type]       [description]
     * @Time   2021-10-22
     * @City   青岛
     * @Author xkyinzhe     <zhonghuaxinxing@sina.cn>
     */
    public static function syncUserBind($l_user_sn, $user_sn, $ifshare=true)
    {
        $userModel = new UserModel();
        if ($ifshare) {
            if ((int)$user_sn == (int)$l_user_sn) {
              throw new \think\Exception("不能自己推荐自己".$user_sn, 404);
            }
            $l_user_info = $userModel
                    ->where([['user_sn','=',$l_user_sn]])
                    ->field('`user_sn`,`user_id`,`is_bind`,`level`,`l_user_sn`,`l_l_user_sn`')
                    ->find();
            if (!$l_user_info) {
                throw new \think\Exception("推荐人用户信息不存在", 404);
            }
            if ($l_user_info['level'] <= 1) {
                throw new \think\Exception("推荐人等级不满足推荐条件，请重试", 404);
            }
            $user_info = $userModel->where([['user_sn','=',$user_sn]])->field('`user_id`,`user_sn`,`user_name`,`level`,`l_user_sn`,`is_all_bind`')->find();
            if (!$user_info) {
                throw new \think\Exception("会员信息不存在", 404);
            }
            if($user_info['l_user_sn'] > 0){
              throw new \think\Exception("会员已经绑定", 404);
            }
            $user_data = [];
            $user_data['l_user_sn'] = $l_user_sn;
            $user_data['l_l_user_sn'] = $l_user_info['l_user_sn'];
            $user_data['l_l_l_user_sn'] = $l_user_info['l_l_user_sn'];
            $user_data['bind_time'] = date('Y-m-d H:i:s'); // 写入绑定时间
            $user_res = $userModel->where([['user_sn','=',$user_sn]])->find()->save($user_data); // 更新上级信息
            $user_info = $userModel->where([['user_sn','=',$user_sn]])->field('`user_id`,`user_sn`,`level`,`l_user_sn`')->find();
            if (!$user_info) {
                throw new \think\Exception("会员信息不存在", 404);
            }
            // 增加新会员的数据量统计
            self::syncCheckUp($user_sn, $l_user_sn, $user_sn, $l_user_sn, $user_info['level'], 'chanageUp');
        }
    }
    /**
     * @xk 执行换绑上级操作
     *
     * @method syncChanageUser
     * @param  [type]          $user_sn                   [description]
     * @param  [type]          $l_user_sn                 [description]
     * @return [type]          [description]
     * @Time   2021-11-09
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public static function syncChanageUser($user_sn, $l_user_sn)
    {
        
        $userModel = new UserModel();
        $sendMsgServices = new SendMsg();
        if ((int)$user_sn == (int)$l_user_sn) {
          throw new \think\Exception("不能自己推荐自己".$user_sn, 404);
        }
          
        $l_user_info = [];
        if ($l_user_sn != '-1') {
               
            //   dump($l_user_sn);die;
            $l_user_info = $userModel
                ->where([['user_sn','=',$l_user_sn]])
                ->field('`user_sn`,`user_id`,`is_bind`,`level`,`l_user_sn`,`l_l_user_sn`')
                ->find();
                //  die("asd");
            if (!$l_user_info) {
                throw new \think\Exception("推荐人用户信息不存在", 404);
            }
            if ($l_user_info['level'] <= 1) {
                throw new \think\Exception("推荐人等级不满足推荐条件，请重试", 404);
            }
        }
     
        $user_info = $userModel->where([['user_sn','=',$user_sn]])->field('`user_id`,`user_sn`,`user_name`,`level`,`l_user_sn`,`is_all_bind`')->find();
        if (!$user_info) {
            throw new \think\Exception("会员信息不存在", 404);
        }
        
        $user_data = [];
        $user_data['l_user_sn'] = $l_user_sn;
        $user_data['l_l_user_sn'] = $l_user_info ? $l_user_info['l_user_sn'] : '-1';
        $user_data['l_l_l_user_sn'] = $l_user_info ? $l_user_info['l_l_user_sn'] : '-1';
        $user_data['bind_time'] = date('Y-m-d H:i:s'); // 写入绑定时间
        $user_res = $userModel->where([['user_sn','=',$user_sn]])->find()->save($user_data);
        // 修改当前会员下级的上级的上级
        $l_user_data = [];
        $l_user_data['l_l_user_sn'] = $l_user_sn;
        $l_user_data['l_l_l_user_sn'] = $l_user_info ? $l_user_info['l_user_sn'] : '-1';
        $l_user_data['bind_time'] = date('Y-m-d H:i:s'); // 写入绑定时间
        $l_user_res = $userModel->where([['l_user_sn','=',$user_sn]])->save($l_user_data);
        //  修改当前会员下级的上级的上级的上级
        $l_l_user_data = [];
        $l_l_user_data['l_l_l_user_sn'] = $l_user_sn;
        $l_l_user_data['bind_time'] = date('Y-m-d H:i:s'); // 写入绑定时间
        $l_l_user_res = $userModel->where([['l_l_user_sn','=',$user_sn]])->save($l_l_user_data);
        if($user_info['l_user_sn'] != $l_user_sn){
          // 换绑推送
          if($user_info['is_all_bind'] == 0){
            $content = '尊敬的用户您好，您的好友【'.$user_info['user_name'].'】于'.date('Y-m-d H:i:s').'通过您的分享进入商城了；【'.$user_info['user_name'].'】通过此次分享，消费成功后方可绑定为您的会员,感谢您的关注与分享！';
            $push_data = [];
            $push_data['create_user_sn'] = $user_info['user_sn'];
            $push_data['user_name'] = $user_info['user_name'];
            $push_data['time'] = date('Y-m-d H:i:s');
            $sendMsgServices->sendPushMsg($user_info['l_user_sn'], '新客户加入通知', $content, 2, $push_data);
          }
       
          // 开始同步调整 对应保有等级处理
          if ($user_info['l_user_sn'] > 0) {
              // 原来会员的上级存在
              self::syncCheckUp($user_sn, $user_info['l_user_sn'], $user_sn, $user_info['l_user_sn'], $user_info['level'], 'chanageOut');
          }
          // 增加新会员的数据量统计
          self::syncCheckUp($user_sn, $l_user_sn, $user_sn, $l_user_sn, $user_info['level'], 'chanageUp');
        }

    }
    /**
     * @xk 发放其他收益
     *
     * @method sendBackMoney
     * @param  [type]        $user_sn                   [description]
     * @param  [type]        $money                     [description]
     * @param  [type]        $content                   [description]
     * @return [type]        [description]
     * @Time   2021-11-09
     * @City   青岛
     * @Author xkyinzhe      <zhonghuaxinxing@sina.cn>
     */
    public static function syncSendBackMoney($user_sn, $money, $content)
    {
        if ($money <= 0) {
            throw new \think\Exception("请输入需要发放的其他收益", 404);
        }
        if ($content == '') {
            throw new \think\Exception("请输入本次发放的备注", 404);
        }
        $backMoneyModel = new BackMoneyModel();
        $userModel = new UserModel();
        $back_money_data['sub_order_sn'] = $backMoneyModel->getCodeNo('xmd'.date('YmdHis'), 20, 1, 'sub_order_sn');
        $back_money_data['create_user_sn'] = '0000000000001'; // 推送人 后台
        $back_money_data['user_sn'] = $user_sn;
        $back_money_data['act'] = 10; // 类型 平台发放
        $back_money_data['is_finance'] = 0; // 是否结算 未结算  同意出账
        $back_money_data['money'] = $money; // 代理佣金
        $back_money_data['content'] = $content;
        $backMoneyModel->create($back_money_data); // 写入平台发放记录
    }


    /**
     * @xk 会员佣金结算入口  在这里进行分流处理广告佣金 代理佣金 评级奖
     *
     * @method syncBackMoney
     * @param  [type]        $sub_order_sn              [description]
     * @param  [type]        $push_user_sn              [description]
     * @param  [type]        $user_sn                   [description]
     * @param  float         $achievement_price         [description]
     * @param  integer       $is_first                  [description]
     * @return [type]        [description]
     * @Time   2021-10-28
     * @City   青岛
     * @Author xkyinzhe      <zhonghuaxinxing@sina.cn>
     */
    public static function syncBackMoney($sub_order_sn, $push_user_sn, $user_sn, $achievement_price=0.00, $is_first=0, $user_level=0)
    {
        $taskService = new Task();
        $avgBackMoney = self::syncOverAvgBackMoney($sub_order_sn); // 执行佣金发放
        $achievement_res = self::syncUserAchievement($sub_order_sn, $push_user_sn, $user_sn, $achievement_price);
        // $agentBack = self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_sn, $achievement_price, $user_level, 0, 0, 0);
        // 此处将代理佣金处理 及时发放到计划任务中 不单独进行处理 2022-08-24
        $msgData = ['time' => date('YmdHis'), 'msgId'=>$sub_order_sn, 'user_sn' => $push_user_sn,'l_user_sn'=>$user_sn,'achievement_price'=>$achievement_price,'level'=>$user_level,'jobAction' => 'syncAgentBackMoney'];
        $delay = 10;
        $taskService->put($msgData, $delay);
        // 全部结束执行订单 结算
        // $subOrderModel = new SubOrderModel();
        // $sub_order_res = $subOrderModel->where([['sub_order_sn','=',$sub_order_sn]])->save(['is_finance'=>1,'finance_time'=>date('Y-m-d H:i:s')]); // 写入订单结算
    }
    /**
     * @xk 执行广告佣金发放
     *
     * @method syncAdvBackMoney
     * @param  [type]           $sub_order_sn              [description]
     * @param  [type]           $push_user_sn              [description]
     * @param  [type]           $user_sn                   [description]
     * @param  [type]           $achievement_price         [description]
     * @param  boolean          $is_first                  [description]
     * @return [type]           [description]
     * @Time   2021-10-28
     * @City   青岛
     * @Author xkyinzhe         <zhonghuaxinxing@sina.cn>
     */
    public static function syncAdvBackMoney($sub_order_sn='', $push_user_sn='', $user_sn='', $type='create', $goods_order_sn='',$all_count = 1)
    {
        $userModel = new UserModel();
        $orderModel = new OrderModel();
        $subOrderModel = new SubOrderModel();
        $goodsOrderModel = new GoodsOrderModel();
        $backMoneyModel = new BackMoneyModel();
        $back_money_data = [];
        $condition = [];
        $back_money_data = [];
        $back_money = 0.00;
        $user_info = $userModel
                  ->alias('u')
                  ->where([['u.user_sn','=',$user_sn]])
                  ->leftJoin('userLevel ul', 'ul.level=u.level')
                  ->field('u.`user_sn`,u.`l_user_sn`,u.`level`,ul.`agency_bili`,ul.`only_agency_bili`')
                  ->find();
        $is_can_create = 0;
        switch ($type) {
          case 'create':
              $condition[] = ['sub_order_sn','=',$sub_order_sn];
              $condition[] = ['status','in','1.1,2.1'];
              $back_money_data['sub_order_sn'] = $sub_order_sn; // 关联订单编号
              $back_money_data['create_user_sn'] = $push_user_sn; // 下单人编号
              $back_money_data['user_sn'] = $user_sn;
              $back_money_data['user_level'] = $user_info['level'];
              $back_money_data['act'] = 1; // 类型 广告佣金 2 3 4 5
              $content = '用户'.$push_user_sn.'下单产生广告佣金';
              $is_can_create = 1;
            break;
          case 'refund':
            // 会员退款 佣金订单扣除&&写入退款佣金记录
            $condition[] = ['sub_order_sn','=',$sub_order_sn];
            $condition[] = ['goods_order_sn','=',$goods_order_sn];
            $condition[] = ['status','in','5.13,5.25']; // 申请退款的情况下
            $back_money_data['sub_order_sn'] = $sub_order_sn; // 关联订单编号
            $back_money_data['create_user_sn'] = $push_user_sn; // 下单人编号
            $back_money_data['user_sn'] = $user_sn;
            $back_money_data['user_level'] = $user_info['level'];
            $back_money_data['act'] = 11; // 类型 订单退款
            $content = '用户'.$push_user_sn.'申请退款驳回佣金';
            if($user_sn > 0){
              $is_can_create = 1;
            }
            break;
        }
        // 获取佣金记录
        $goods_list = $goodsOrderModel
                    ->where($condition)
                    ->field('`goods_id`,`all_achievement_price`,`bonus_type`,`bonus_price`,`next_bonus_price`,`is_buy`,`buy_num`')
                    ->select()
                    ->toArray();
        $back_money = 0.00;
        $achievement_price = 0.00;
        foreach ($goods_list as $value) {
            $achievement_price += $value['all_achievement_price'];
            switch ($value['bonus_type']) {
            case '0':
              $money = 0.00;
              $back_bili = config('web_config.first_bili');
              if ($value['is_buy'] == 1) {
                  $back_bili = config('web_config.next_bili');
              }
              // 开始计算
              $money = (float)$value['all_achievement_price']*(float)$back_bili;
              $back_money += $money;
              break;
            case '1':
              if ($value['is_buy'] == 1) {
                  $back_money += (float)$value['next_bonus_price']*(int)$value['buy_num'];
              } else {
                  $back_money += (float)$value['bonus_price']*(int)$value['buy_num'];
              }
              break;
          }
        }
        $back_money_data['is_finance'] = 0; // 是否结算 广告佣金当场结算
        $back_money_data['achievement_price'] = $achievement_price; // 业绩金额
        $back_money_data['money'] = $back_money; // 自购佣金
        $back_money_data['content'] = $content.(float)$back_money.'元';
        // 新增校验无上级 售后订单不产生佣金扣除现象
        if ($back_money_data && (float)$back_money > 0 && (int)$is_can_create == 1) {
            $backMoneyModel->create($back_money_data); // 写入返佣记录
        }else{
          $path = 'backError/syncAdvBackMoney/';
          $content = $sub_order_sn."暂时无法进行佣金返利，相关佣金金额".$back_money."相关返利是否允许".$is_can_create;
          createLog($path, $content);
        }
        if($type == 'refund' && $all_count <= 0){
          self::syncOverAvgBackMoney($sub_order_sn);
        }
    }
    /**
     * @xk 执行广告佣金发放到用户账户
     * @method                                      syncOverAvgBackMoney
     * @param                                       [type] $sub_order_sn  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-24Tfalse13:false32:false12+080
     */
    public static function syncOverAvgBackMoney($sub_order_sn)
    {
        $userModel = new UserModel();
        $backMoneyModel = new BackMoneyModel();
        $sendMsg = new SendMsg();
        $back_list = $backMoneyModel
                  ->where([['sub_order_sn','=',$sub_order_sn],['act','=','1'],['is_finance','=',0]])
                  ->field('`back_money_id`,`money`,`user_sn`')
                  ->select()
                  ->toArray();
        if ($back_list) {
            foreach ($back_list as $key => $value) {
                $back_data = [];
                $back_data['is_finance'] = 1;
                $back_data['finance_time'] = date('Y-m-d H:i:s');
                $backMoneyModel->where([['sub_order_sn','=',$sub_order_sn],['act','in','1']])->save($back_data);
                // 开始写入用户佣金  开始写入用户总佣金
                $back_res = $userModel->where([['user_sn','=',$value['user_sn']]])->inc('back_money', (float)$value['money'])->update();
                $back_res = $userModel->where([['user_sn','=',$value['user_sn']]])->inc('all_back_money', (float)$value['money'])->update();
            }
        }
        $back_listx = $backMoneyModel
                  ->where([['sub_order_sn','=',$sub_order_sn],['act','=','11'],['is_finance','=',0]])
                  ->field('`back_money_id`,`money`,`user_sn`')
                  ->select()
                  ->toArray();
        if ($back_listx) {
            foreach ($back_listx as $key => $value) {
                $back_data = [];
                $back_data['is_finance'] = 1;
                $back_data['finance_time'] = date('Y-m-d H:i:s');
                $backMoneyModel->where([['sub_order_sn','=',$sub_order_sn],['act','in','11']])->save($back_data);
                // 开始写入用户佣金  开始写入用户总佣金
                $back_res = $userModel->where([['user_sn','=',$value['user_sn']]])->dec('back_money', (float)$value['money'])->update();
                $back_res = $userModel->where([['user_sn','=',$value['user_sn']]])->dec('all_back_money', (float)$value['money'])->update();
            }
        }
    }
    /**
     * @xk 计算代理佣金和平级奖励
     * @method                                      syncAgentBackMoney
     * @param                                       [type] $sub_order_sn  [description]
     * @param                                       [type] $push_user_sn  [description]
     * @param                                       [type] $user_sn  [description]
     * @param                                       [type] $achievement_price  [description]
     * @param                                       [type] $last_level  [description]
     * @param                                       [type] $dep  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-23Tfalse18:false42:false35+080
     */
    public static function syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_sn, $achievement_price, $last_level, $dep=0, $level4_dep=0, $level5_dep=0)
    {
        $userModel = new UserModel();
        $userLevelModel = new UserLevelModel();
        $backMoneyModel = new BackMoneyModel();
        $user_info = $userModel
              ->alias('u')
              ->where([['u.user_sn','=',$user_sn]])
              ->leftJoin('userLevel ul', 'ul.level=u.level')
              ->field('u.`user_sn`,u.`l_user_sn`,u.`level`,ul.`agent_bili`,ul.`avg_bili`,ul.`only_agent_bili`')
              ->find();
        if (!$user_info) {
            throw new \think\Exception("用户信息异常", 404);
        }
        // var_dump($user_info); die();
        // 没有计算过县级代理返利 开始执行代理佣金返利
        $back_money_data = [];
        $back_money = 0.00;
        $back_money_data['sub_order_sn'] = $sub_order_sn; // 关联订单编号
        $back_money_data['create_user_sn'] = $push_user_sn; // 下单人编号
        $back_money_data['user_sn'] = $user_sn;
        $back_money_data['achievement_price'] = $achievement_price; // 业绩金额
        $back_money_data['user_level'] = $user_info['level']; // 代理等级
        $back_money_data['is_finance'] = 0; // 是否结算 代理佣金按月出账
        if ($last_level <= $user_info['level'] && $user_info['level'] >= 3) {
            switch ($user_info['level']) {
              case '3':
                if ($dep <= 0) {
                    // 执行代理佣金发放
                  $back_money_data['agent_bili'] = $user_info['agent_bili']; // 代理佣金比例
                  $back_money = $achievement_price*$user_info['agent_bili']; // 计算自购代理佣金
                  $back_money_data['money'] = $back_money; // 代理佣金
                  $back_money_data['act'] = 2; // 类型 代理佣金
                  $back_money_data['content'] = '用户'.$push_user_sn.'下单产生代理佣金'.$back_money.'元';
                    if ($back_money_data) {
                        $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                        if ($user_info['l_user_sn'] > 0) {
                            // 当前等级不满足返利条件 开始执行给上级返利
                            self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price, $user_info['level'], $dep+1, $level4_dep, $level5_dep);
                        }
                    }
                } else {
                  $back_money_data['agent_bili'] = 0; // 代理佣金比例
                  $back_money = 0.00; // 计算自购代理佣金
                  $back_money_data['act'] = 5; // 类型 代理佣金
                  $back_money_data['money'] = $back_money; // 代理佣金
                  if ($back_money_data) {
                      $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                      if ($user_info['l_user_sn'] > 0) {
                          // 当前等级不满足返利条件 开始执行给上级返利
                          self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price, $last_level, $dep, $level4_dep, $level5_dep);
                      }
                  }
                }
                break;
              case '4':
                $dep = 2; // 已经参与到时代返利 所以县代都不在参与计算
                // 当前等级是
                switch ($level4_dep) {
                  case '0':
                    // 第一次进入 需要判断 当前用户和下单人之间的关系 如果是同一个人 或则上次计算等级小于当前等级 则获得代理佣金

                    // 判断是否需要极差计算 如果不需要则直接进入第二次返利 2%
                    if ($last_level < $user_info['level'] || $push_user_sn == $user_sn) {
                        // 上个等级小于这个数 计算极差\
                        $last_level_bili = 0;
                        if($last_level < $user_info['level']){
                          $last_level_bili = $userLevelModel
                                          ->where([['level','=',$last_level]])
                                          ->value('agent_bili');
                        }

                        $agent_bili = $user_info['agent_bili'] - $last_level_bili;
                        $back_money_data['agent_bili'] = $agent_bili; // 代理佣金比例
                        $back_money = $achievement_price*$agent_bili; // 计算自购代理佣金
                        $back_money_data['content'] = '用户'.$push_user_sn.'下单产生代理佣金'.$back_money.'元';
                        $back_money_data['act'] = 2; // 类型 代理佣金
                        $level4_dep = 1;
                    } else {
                        // 上个等级就是这个数 不计算极差 直接返佣
                      $back_money_data['agent_bili'] = $user_info['avg_bili']; // 代理佣金比例
                      $back_money = $achievement_price*$user_info['avg_bili']; // 计算自购代理佣金
                      $back_money_data['content'] = '用户'.$push_user_sn.'下单产生平级佣金'.$back_money.'元';
                        $back_money_data['act'] = 3; // 类型 代理佣金
                        $level4_dep = 2;
                    }
                    $back_money_data['money'] = $back_money; // 代理佣金
                    if ($back_money_data) {
                        $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                        if ($user_info['l_user_sn'] > 0) {
                            // 当前等级不满足返利条件 开始执行给上级返利
                            self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price, $user_info['level'], $dep, $level4_dep, $level5_dep);
                        }
                    }
                    break;
                  case '1':
                     // 上个等级就是这个数 不计算极差 直接返佣
                     $back_money_data['agent_bili'] = $user_info['avg_bili']; // 代理佣金比例
                     $back_money = $achievement_price*$user_info['avg_bili']; // 计算自购代理佣金
                     $back_money_data['act'] = 3; // 类型 代理佣金
                     $level4_dep = 2;
                     $back_money_data['money'] = $back_money; // 代理佣金
                     if ($back_money_data) {
                         $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                         if ($user_info['l_user_sn'] > 0) {
                             // 当前等级不满足返利条件 开始执行给上级返利
                             self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price, $user_info['level'], $dep, $level4_dep, $level5_dep);
                         }
                     }
                    break;
                  case '2':
                      // 1%
                      $back_money_data['agent_bili'] = $user_info['avg_bili']; // 代理佣金比例
                      $back_money = $achievement_price*$user_info['avg_bili']; // 计算自购代理佣金
                      $back_money_data['act'] = 3; // 类型 代理佣金
                      $level4_dep = 3;
                      $back_money_data['money'] = $back_money; // 代理佣金
                      if ($back_money_data) {
                          $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                          if ($user_info['l_user_sn'] > 0) {
                              // 当前等级不满足返利条件 开始执行给上级返利
                              self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price, $user_info['level'], $dep, $level4_dep, $level5_dep);
                          }
                      }
                    break;
                  default:
                    $back_money_data['agent_bili'] = 0; // 代理佣金比例
                    $back_money = 0.00; // 计算自购代理佣金
                    $back_money_data['act'] = 5; // 类型 代理佣金
                    $back_money_data['money'] = $back_money; // 代理佣金
                    $level4_dep = 3;
                    createLog("bili/", json_encode($back_money_data));
                    if ($back_money_data) {
                        $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                        if ($user_info['l_user_sn'] > 0) {
                            // 当前等级不满足返利条件 开始执行给上级返利
                            self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price, $last_level, $dep, $level4_dep, $level5_dep);
                        }
                    }
                    break;
                }
                break;
              case '5':
                // 当前等级是
                $dep = 2;
                $level4_dep = 3;
                switch ($level5_dep) {
                  case '0':
                    // 判断是否需要极差计算 如果不需要则直接进入第二次返利 2%
                    if ($last_level < $user_info['level'] || $push_user_sn == $user_sn) {
                        // 上个等级小于这个数 计算极差
                        $last_level_bili = 0;
                        if($last_level < $user_info['level']){
                          $last_level_bili = $userLevelModel
                                          ->where([['level','=',$last_level]])
                                          ->value('agent_bili');
                        }
                        $agent_bili = $user_info['agent_bili'] - $last_level_bili;
                        $back_money_data['agent_bili'] = $agent_bili; // 代理佣金比例
                        $back_money = $achievement_price*$agent_bili; // 计算自购代理佣金
                        $back_money_data['content'] = '用户'.$push_user_sn.'下单产生平级佣金'.$back_money.'元';
                        $back_money_data['act'] = 2; // 类型 代理佣金
                        $level5_dep = 1;
                    } else {
                        // 上个等级就是这个数 不计算极差 直接返佣
                      $back_money_data['agent_bili'] = $user_info['avg_bili']; // 代理佣金比例
                      $back_money = $achievement_price*$user_info['avg_bili']; // 计算自购代理佣金
                      $back_money_data['content'] = '用户'.$push_user_sn.'下单产生平级佣金'.$back_money.'元';
                        $back_money_data['act'] = 3; // 类型 代理佣金
                        $level5_dep = 2;
                    }
                    $back_money_data['money'] = $back_money; // 代理佣金
                    if ($back_money_data) {
                        $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                        if ($user_info['l_user_sn'] > 0) {
                            // 当前等级不满足返利条件 开始执行给上级返利
                            self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price, $user_info['level'], $dep, $level4_dep, $level5_dep);
                        }
                    }
                    break;
                  case '1':
                     // 上个等级就是这个数 不计算极差 直接返佣
                     $back_money_data['agent_bili'] = $user_info['avg_bili']; // 代理佣金比例
                     $back_money = $achievement_price*$user_info['avg_bili']; // 计算自购代理佣金
                     $back_money_data['act'] = 3; // 类型 代理佣金
                     $level5_dep = 2;
                     $back_money_data['money'] = $back_money; // 代理佣金
                     if ($back_money_data) {
                         $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                         if ($user_info['l_user_sn'] > 0) {
                             // 当前等级不满足返利条件 开始执行给上级返利
                             self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price, $user_info['level'], $dep, $level4_dep, $level5_dep);
                         }
                     }
                    break;
                  case '2':
                      // 1%
                      $back_money_data['agent_bili'] = $user_info['avg_bili']; // 代理佣金比例
                      $back_money = $achievement_price*$user_info['avg_bili']; // 计算自购代理佣金
                      $back_money_data['act'] = 3; // 类型 代理佣金
                      $level5_dep = 3;
                      $back_money_data['money'] = $back_money; // 代理佣金
                      if ($back_money_data) {
                          $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                          if ($user_info['l_user_sn'] > 0) {
                              // 当前等级不满足返利条件 开始执行给上级返利
                              self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price, $user_info['level'], $dep, $level4_dep, $level5_dep);
                          }
                      }
                    break;
                    default:
                      // 1%
                      $back_money_data['agent_bili'] = 0; // 代理佣金比例
                      $back_money = 0.00; // 计算自购代理佣金
                      $back_money_data['act'] = 5; // 类型 代理佣金
                      $back_money_data['money'] = $back_money; // 代理佣金
                      $level5_dep = 3;
                      if ($back_money_data) {
                          $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                          if ($user_info['l_user_sn'] > 0) {
                              // 当前等级不满足返利条件 开始执行给上级返利
                              self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price, $last_level, $dep, $level4_dep, $level5_dep);
                          }
                      }
                      break;
                }
                break;
              default:
                // 1%
                $back_money_data['agent_bili'] = 0; // 代理佣金比例
                $back_money = 0.00; // 计算自购代理佣金
                $back_money_data['act'] = 5; // 类型 代理佣金
                $back_money_data['money'] = $back_money; // 代理佣金
                if ($back_money_data) {
                    $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                    if ($user_info['l_user_sn'] > 0) {
                        // 当前等级不满足返利条件 开始执行给上级返利
                        self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price, $last_level, $dep, $level4_dep, $level5_dep);
                    }
                }
                break;
            }
        } else {
            $back_money_data['agent_bili'] = 0; // 代理佣金比例
            $back_money = 0.00; // 计算自购代理佣金
            $back_money_data['act'] = 5; // 类型 代理佣金
            $back_money_data['money'] = $back_money; // 代理佣金
            if ($back_money_data) {
                $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                if ($user_info['l_user_sn'] > 0) {
                    // 当前等级不满足返利条件 开始执行给上级返利
                    self::syncAgentBackMoney($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price, $last_level, $dep, $level4_dep, $level5_dep);
                }
            }
        }
    }
    /**
     * @xk 执行会员业绩金额写入
     *
     * @method syncUserAchievement
     * @param  [type]              $sub_order_sn              [description]
     * @param  [type]              $user_sn                   [description]
     * @param  [type]              $achievement_price         [description]
     * @return [type]              [description]
     * @Time   2021-10-28
     * @City   青岛
     * @Author xkyinzhe            <zhonghuaxinxing@sina.cn>
     */
    public static function syncUserAchievement($sub_order_sn='', $push_user_sn='', $user_sn='', $achievement_price=0.00)
    {
        $userModel = new UserModel();
        $userAchievementModel = new UserAchievementModel();
        $taskService = new Task();
        if ($achievement_price <= 0) {
            throw new \think\Exception("业绩金额小于等于0 无需进行业绩统计", 404);
        }
        $user_info = $userModel->where([['user_sn','=',$user_sn]])->field('`l_user_sn`,`level`')->find();
        if (!$user_info) {
            throw new \think\Exception($user_sn.'会员信息异常', 404);
        }
        $count = $userAchievementModel->where([['user_sn','=',$user_sn],['sub_order_sn','=',$sub_order_sn],['create_user_sn','=',$push_user_sn]])->count();
        if ($count <= 0) {
            $achievement_data = [];
            $achievement_data['sub_order_sn'] = $sub_order_sn; // 关联订单编号
            $achievement_data['user_sn'] = $user_sn; // 关联用户编号
            $achievement_data['create_user_sn'] = $push_user_sn; // 下单人
            $achievement_data['achievement_price'] = $achievement_price; // 业绩金额
            $userAchievementModel->create($achievement_data); // 写入当前用户的业绩记录
            // 增加会员业绩
            $userModel
            ->where([['user_sn','=',$user_sn]])
            ->inc('all_achievement_price', $achievement_price)
            ->update();
            if ($user_sn == $push_user_sn) {
                // 增加会员业绩
                $userModel
                ->where([['user_sn','=',$user_sn]])
                ->inc('agent_achievement_price', $achievement_price)
                ->update();
            }
        }
        if ($user_info['l_user_sn'] > 0) {
            // 如果当前用户存在上级 则针对上级进行业绩金额写入
            self::syncUserAchievement($sub_order_sn, $push_user_sn, $user_info['l_user_sn'], $achievement_price);
        }
        // 此处标记 可能存在问题
        if (!$user_info['l_user_sn'] || $user_info['l_user_sn'] == '' || $user_info['l_user_sn'] <= 0) {
            self::doCheckUp($push_user_sn);
        }
    }
    /**
     * @xk 进行会员升级检测
     * @method                                      doCheckUp
     * @param                                       string $user_sn  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-03-09Tfalse13:false25:false36+080
     */
    public static function doCheckUp($user_sn = '')
    {
        $taskService = new Task();
        if (!$user_sn || $user_sn == '') {
            throw new \think\Exception($user_sn.'会员信息异常', 404);
        }
        // 循环完毕 可以开始执行第二个步骤计划 执行返利
        $msgData = ['time' => date('YmdHis'), 'user_sn' => $user_sn, 'jobAction' => 'syncCheckUp'];
        $check_now_time =  checkNowTime();
        // 如果是在统计过程中 则自动向后延期九个半小时
        $delay = $check_now_time==1?30:34230;
        $taskService->put($msgData, $delay);
        $content = $user_sn.'========执行升级计划';
        createLog('check_up_plan/', $content);
    }
    /**
     * @xk 执行会员升级检测
     *
     * @method checkUp
     * @param  [type]     $user_sn                   [description]
     * @param  [type]     $level                     [description]
     * @return [type]     [description]
     * @Time   2021-10-28
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public static function checkUpx($user_sn)
    {
        $userModel = new UserModel();
        $userLevelModel = new UserLevelModel();
        $userAchievementModel = new UserAchievementModel();
        $userUpLogModel = new UserUpLogModel();
        $user_info = $userModel
                    ->alias('u')
                    ->leftJoin('user lu', 'lu.user_sn=u.l_user_sn')
                    ->where([['u.user_sn','=',$user_sn]])
                    ->field('u.`l_user_sn`,lu.`level` as l_level,u.`level`,u.`level_3_count`,u.`level_4_count`')
                    ->find();
        $user_info = $user_info ? $user_info->toArray() : [];
        if (!$user_info) {
            $content = $user_sn.'========用户信息不存在';
            createLog('check_log/', $content);
            exit();
        }
        $level = $user_info['level'];
        if ($level == 1) {
            $level = 2;
        }
        if ($level <= 4) {
            $new_level = (int)$level+1; // 当前等级+1
        } else {
            $new_level = 5;
        }
        $user_level_info = $userLevelModel
                        ->where([['level','=',$new_level]])
                        ->field('`level`,`only_achievement_price`,`team_achievement_price`,`child_num`')
                        ->find();
        $is_up = 0;
        $content = $user_sn.'========'.$level;
        createLog('check_log/', $content);
        switch ((int)$level) {
          case 2:
            // 当前会员属于vip会员 查询当前会员本人业绩 和伞下总业绩
            $team_achievement_price = $userAchievementModel
                                      ->where([['user_sn','=',$user_sn]])
                                      ->sum('achievement_price');
            if ($team_achievement_price >= $user_level_info['team_achievement_price']) {
                // 满足升级条件 执行升级
              $is_up = 1; //可以执行升级 修改用户会员等级 写入用户升级日志
            }
            break;
          case 3:
            // 查询 直推存在几个同等级会员
            $count = $user_info['level_3_count'];
            $content = $user_sn.'========'.$level."-------------------".$count;
            createLog('check_log_count/', $content);
            if ($count >= $user_level_info['child_num']) {
                $is_up = 1; // 满足升级条件
            }
            break;
          case 4:
            // 查询 直推存在几个同等级会员
            $count = $user_info['level_4_count'];
            $content = $user_sn.'========'.$level."-------------------".$count;
            createLog('check_log_count/', $content);
            if ($count >= $user_level_info['child_num']) {
                $is_up = 1; // 满足升级条件
            }
            break;
        }
        switch ($is_up) {
          case '1':
            $user_up_data = [];
            $user_up_data['user_sn'] = $user_sn; // 会员
              $user_up_data['old_level'] = $level; // 升级之前会员等级  2
              $user_up_data['level'] = $new_level; // 升级后会员等级
              $userUpLogModel->create($user_up_data); // 写入用户升级记录
              $user_save_data = [];
              $user_save_data['level'] = $new_level;
              // if($new_level == 3){
              // 2022-05-28 此处应销售需求，更改成为代理时间为 等级大于县代的情况下动态更新代理时间
                $user_save_data['agent_time'] = date('Y-m-d H:i:s');
              // }
              $userModel->where([['user_sn','=',$user_sn]])
                      ->find()
                      ->save($user_save_data); // 修改当前用户等级 修改当前代理时
              if ($user_info && $user_info['l_user_sn'] > 0) {
                  // 执行上级会员保有数量同步
                self::syncCheckUp($user_sn, $user_info['l_user_sn'], $user_sn, $user_info['l_user_sn'], $level, 'desc'); // 执行会员等级更换
                self::syncCheckUp($user_sn, $user_info['l_user_sn'], $user_sn, $user_info['l_user_sn'], $new_level, 'inc'); // 执行会员等级更换
              }
            break;
          default:
            if ($user_info && $user_info['l_user_sn'] > 0) {
                self::doCheckUp($user_info['l_user_sn']);
            }
            break;
        }
    }
    /**
     * @xk 查询每条线共有几个会员
     * @method                                      getChildFirstNum
     * @param                                       string $user_sn  [description]
     * @param                                       string $level  [description]
     * @param                                       int $all_count  [description]
     * @param                                       int $need_num  [description]
     * @param                                       array $user_array  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-03-16Tfalse17:false38:false27+080
     */
    public static function getChildFirstNum($user_sn = '', $level = 0, $all_count = 0, $need_num = 0, $user_array = [])
    {
        $userModel = new UserModel();
        // 开始获取 下一级会员
        $l_user_list = $userModel
                ->where([['l_user_sn','=',$user_sn],['status','=',1],['level','>',1]])
                ->field('`user_sn`,`level`')
                ->select()
                ->toArray();
        if ($l_user_list) {
            foreach ($l_user_list as $key => $value) {
                if ($value['level'] >= $level) {
                    // 当前等级大于等级查询等级
                    $all_count ++;
                    unset($l_user_list[$key]); // 去除对应的线
                    if ($all_count >= $need_num) {
                        break;
                    }
                }
            }
            if ($l_user_list && $all_count < $need_num) {
                foreach ($l_user_list as $key => $value) {
                    // 只要存在一个 就立即返回
                    $all_count += self::getChildNumCount($value['user_sn'], $level);
                    if ($all_count >= $need_num) {
                        break;
                    }
                }
            }
        }
        return $all_count;
    }
    /**
     * @xk 查询下级当前等级人数统计
     * @method                                      getChildNumCount
     * @param                                       string $user_sn  [description]
     * @param                                       [type] $level  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-03-16Tfalse14:false29:false24+080
     */
    public static function getChildNumCount($user_sn='', $level=0)
    {
        $userModel = new UserModel();
        // 开始获取 下一级会员
        $l_user_list = $userModel
                  ->where([['l_user_sn','=',$user_sn],['status','=',1],['level','>',1]])
                  ->field('`user_sn`,`level`')
                  ->select()
                  ->toArray();
        $count = 0;
        if ($l_user_list) {
            foreach ($l_user_list as $key => $value) {
                if ($value['level'] >= $level) {
                    $count = 1;
                    break;
                }
            }
            if ($count <= 0) {
                // 全部本层不存在
                foreach ($l_user_list as $key => $value) {
                    $count = self::getChildNumCount($value['user_sn'], $level);
                    if ($count >= 1) {
                        break;
                    }
                }
            }
        }
        return $count;
    }
    /**
     * @xk 获取下级大于当前等级的会员
     *
     * @method getChildLevel
     * @param  [type]        $user_sn                   [description]
     * @param  [type]        $user_level                [description]
     * @return [type]        [description]
     * @Time   2021-11-23
     * @City   青岛
     * @Author xkyinzhe      <zhonghuaxinxing@sina.cn>
     */
    public static function getChildLevel($user_sn, $user_level)
    {
        $userModel = new UserModel();
        $user_list = $userModel->where([['l_user_sn','=',$user_sn]])->field('`user_sn`,`l_user_sn`,`level`')->select()->toArray();
        if ($user_list) {
            foreach ($user_list as $key => $value) {
                if ($value['level'] > $user_level) {
                    return $value['level'];
                    break;
                }
                self::getChildLevel($value['user_sn'], $user_level);
            }
        }
    }
    /**
     * @xk 开始执行余额支付
     *
     * @method shopPay
     * @param  [type]     $data                      [description]
     * @return [type]     [description]
     * @Time   2021-10-29
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public static function shopPay($data)
    {
        $orderModel = new OrderModel();
        $userModel = new UserModel();
        $orderServices = new OrderServices();
        $backMoneyModel = new BackMoneyModel();
        $financeServices = new FinanceServices(); // 财务记录
        $user_sn = isset($data['user_sn']) ? $data['user_sn'] : '';
        $order_sn = isset($data['order_sn']) ? $data['order_sn'] : '';
        $need_pay = isset($data['need_pay']) ? $data['need_pay'] : 0.00;

        if ($user_sn == '') {
            throw new \think\Exception("用户信息错误，请重试", 404);
        }
        if ($order_sn == '') {
            throw new \think\Exception("订单不存在，请重新对接", 404);
        }
        if ($need_pay <= 0) {
            throw new \think\Exception("订单金额小于0 无需进行支付", 404);
        }

        $order_info = $orderModel->where([['order_sn','=',$order_sn]])->field('`order_sn`,`user_sn`,`status`,`pay_status`,`shipping_type`,`order_id`')->find();
        if (!$order_info) {
            throw new \think\Exception("订单不存在", 404);
        }
        if ($order_info['pay_status'] != 0) {
            throw new \think\Exception("订单状态错误", 404);
        }
        $user_info = $userModel->where([['user_sn','=',$user_sn]])->field('`back_money`')->find();
        if (!$user_info) {
            throw new \think\Exception("用户信息不存在", 404);
        }
        if ((float)$user_info['back_money'] < (float)$need_pay) {
            throw new \think\Exception("余额不足以支付订单", 404);
        }
        // 用户余额充足 并足以支付订单金额
        // 执行用户余额扣除
        $back_money_data = [];
        $back_money_data['sub_order_sn'] = $order_sn; // 关联订单编号
        $back_money_data['create_user_sn'] = $user_sn; // 下单人编号
        $back_money_data['user_sn'] = $user_sn;
        $back_money_data['achievement_price'] = 0; // 业绩金额
        $back_money_data['user_level'] = 0; // 代理等级
        $back_money_data['agent_bili'] = 0; // 代理佣金比例
        $back_money_data['act'] = 8; // 类型 代理佣金
        $back_money_data['is_finance'] = 1; // 是否结算 代理佣金按月出账
        $back_money_data['finance_time'] = date('Y-m-d H:i:s'); // 结算时间
        $back_money_data['money'] = $need_pay; // 代理佣金
        $back_money_data['content'] = '用户下单消耗佣金'.$need_pay.'元';
        $userModel->where([['user_sn','=',$user_sn]])->dec('back_money', (float)$need_pay)->update();
        $backMoneyModel->create($back_money_data); // 写入用户佣金记录
        // 调整订单状态
        $order_data = [];
        $shipping_type = $order_info['shipping_type'];
        $order_data['status'] = 1;
        // if ($shipping_type == 2) {
        //     $order_data['status'] = 2; //
        //   $order_data['delivery_time'] = date('Y-m-d H:i:s'); // 自提订单记录发货时间
        // }
        $order_data['pay_status'] = 1;
        $order_data['order_id'] = $order_info['order_id'];
        $order_data['pay_type'] = 3;
        $order_data['pay_time'] = date('Y-m-d H:i:s'); // 支付时间
        $order_data['pay_price'] = $need_pay; // 支付金额
        $order_data['pay_code'] = $orderModel->getCodeNo(date('YmdHis'), 25, 1, 'pay_code'); // 支付流水号
        $order_data['pay_order_sn'] = $orderModel->getCodeNo(date('YmdHis'), 25, 1, 'pay_order_sn'); // 支付流水号
        $order_res = $orderModel->find($order_info['order_id'])->save($order_data);
        // 写入余额财务记录
        // $finance_datax = [];
        // $finance_datax['relation_num'] = $order_info['order_sn'];
        // $finance_datax['relation_user_num'] = $order_info['user_sn'];
        // $finance_datax['entry'] = 2;
        // $finance_datax['money'] = $order_data['pay_price'];
        // $finance_datax['pay_order_sn'] = $order_data['pay_order_sn'];
        // $finance_datax['content'] = '用户余额购买商品平台出账';
        // $finance_datax['pay_type'] = 3;
        // $finance_datax['act'] = 1;
        // $financeServices->syncFinance($finance_datax);

        $finance_data = [];
        $finance_data['relation_num'] = $order_info['order_sn'];
        $finance_data['relation_user_num'] = $order_info['user_sn'];
        $finance_data['entry'] = 1;
        $finance_data['money'] = $order_data['pay_price'];
        $finance_data['pay_order_sn'] = $order_data['pay_order_sn'];
        $finance_data['content'] = '用户余额购买商品平台入账';
        $finance_data['pay_type'] = 3;
        $finance_data['act'] = 1;
        $financeServices->syncFinance($finance_data);
        $orderServices->syncSubOrderPay($order_sn);
        return true;
    }
    /**
     * @xk 余额支付子订单
     *
     * @method shopSubPay
     * @param  [type]     $data                      [description]
     * @return [type]     [description]
     * @Time   2021-11-03
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public static function shopSubPay($data)
    {
        $subOrderModel = new SubOrderModel();
        $userModel = new UserModel();
        $orderServices = new OrderServices();
        $backMoneyModel = new BackMoneyModel();
        $financeServices = new FinanceServices();
        $user_sn = isset($data['user_sn']) ? $data['user_sn'] : '';
        $sub_order_sn = isset($data['sub_order_sn']) ? $data['sub_order_sn'] : '';
        $need_pay = isset($data['need_pay']) ? $data['need_pay'] : 0.00;

        if ($user_sn == '') {
            throw new \think\Exception("用户信息错误，请重试", 404);
        }
        if ($sub_order_sn == '') {
            throw new \think\Exception("订单不存在，请重新对接", 404);
        }
        if ($need_pay <= 0) {
            throw new \think\Exception("订单金额小于0 无需进行支付", 404);
        }

        $order_info = $subOrderModel->where([['sub_order_sn','=',$sub_order_sn]])->field('`sub_order_sn`,`user_sn`,`status`,`pay_status`,`shipping_type`,`sub_order_id`')->find();
        if (!$order_info) {
            throw new \think\Exception("订单不存在", 404);
        }
        if ($order_info['pay_status'] != 0) {
            throw new \think\Exception("订单状态错误", 404);
        }
        $user_info = $userModel->where([['user_sn','=',$user_sn]])->field('`back_money`')->find();
        if (!$user_info) {
            throw new \think\Exception("用户信息不存在", 404);
        }
        if ((float)$user_info['back_money'] < (float)$need_pay) {
            throw new \think\Exception("余额不足以支付订单", 404);
        }
        // 用户余额充足 并足以支付订单金额
        // 执行用户余额扣除
        $back_money_data = [];
        $back_money_data['sub_order_sn'] = $sub_order_sn; // 关联订单编号
        $back_money_data['create_user_sn'] = $user_sn; // 下单人编号
        $back_money_data['user_sn'] = $user_sn;
        $back_money_data['achievement_price'] = 0; // 业绩金额
        $back_money_data['user_level'] = 0; // 代理等级
        $back_money_data['agent_bili'] = 0; // 代理佣金比例
        $back_money_data['act'] = 8; // 类型 代理佣金
        $back_money_data['is_finance'] = 1; // 是否结算 代理佣金按月出账
        $back_money_data['finance_time'] = date('Y-m-d H:i:s'); // 结算时间
        $back_money_data['money'] = $need_pay; // 代理佣金
        $back_money_data['content'] = '用户下单消耗佣金'.$need_pay.'元';
        $userModel->where([['user_sn','=',$user_sn]])->dec('back_money', (float)$need_pay)->update();
        $backMoneyModel->create($back_money_data); // 写入代理返佣记录
        // 调整订单状态
        $order_data = [];
        $shipping_type = $order_info['shipping_type'];
        $order_data['status'] = 1;
        // if ($shipping_type == 2) {
        //     $order_data['status'] = 2; //
        //   $order_data['delivery_time'] = date('Y-m-d H:i:s'); // 自提订单记录发货时间
        // }
        $order_data['pay_status'] = 1;
        $order_data['order_id'] = $order_info['order_id'];
        $order_data['pay_type'] = 3;
        $order_data['pay_time'] = date('Y-m-d H:i:s'); // 支付时间
        $order_data['pay_price'] = $need_pay; // 支付金额
        $order_data['pay_code'] = $subOrderModel->getCodeNo(date('YmdHis'), 25, 1, 'pay_code'); // 支付流水号
        $order_data['pay_order_sn'] = $subOrderModel->getCodeNo(date('YmdHis'), 25, 1, 'pay_order_sn'); // 支付流水号
        $order_res = $subOrderModel->find($order_info['sub_order_id'])->save($order_data);
        // 写入余额财务记录

        // $finance_datax = [];
        // $finance_datax['relation_num'] = $order_info['sub_order_sn'];
        // $finance_datax['relation_user_num'] = $order_info['user_sn'];
        // $finance_datax['entry'] = 2;
        // $finance_datax['money'] = $order_data['pay_price'];
        // $finance_datax['pay_order_sn'] = $order_data['pay_order_sn'];
        // $finance_datax['content'] = '用户余额购买商品平台出账';
        // $finance_datax['pay_type'] = 3;
        // $finance_datax['act'] = 2;
        // $financeServices->syncFinance($finance_datax);

        $finance_data = [];
        $finance_data['relation_num'] = $order_info['sub_order_sn'];
        $finance_data['relation_user_num'] = $order_info['user_sn'];
        $finance_data['entry'] = 1;
        $finance_data['money'] = $order_data['pay_price'];
        $finance_data['pay_order_sn'] = $order_data['pay_order_sn'];
        $finance_data['content'] = '用户余额购买商品进行支付';
        $finance_data['pay_type'] = 3;
        $finance_data['act'] = 2;
        $financeServices->syncFinance($finance_data);
        $orderServices->syncOrderGoodsStatus($order_info['sub_order_sn']);
        return true;
    }
    /**
     * @xk 执行用户余额支付退款操作
     *
     * @method shopSubPay
     * @param  [type]     $data                      [description]
     * @return [type]     [description]
     * @Time   2021-11-03
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public static function syncRefundMoney($data)
    {
        $refundOrderModel = new RefundOrderModel(); // 售后处理模型
        $userModel = new UserModel();
        $orderServices = new OrderServices();
        $backMoneyModel = new BackMoneyModel();
        $financeServices = new FinanceServices();
        $user_sn = isset($data['user_sn']) ? $data['user_sn'] : '';
        $refund_order_sn = isset($data['refund_order_sn']) ? $data['refund_order_sn'] : '';
        $need_pay = isset($data['refund_check_price']) ? $data['refund_check_price'] : 0.00;
        if (!$data) {
            throw new \think\Exception("售后订单异常", 404);
        }
        if ($data['status'] != 1.1 && $data['status'] != 2.4) {
            throw new \think\Exception("当前售后订单不处于可以退款状态", 404);
        }
        if ($user_sn == '') {
            throw new \think\Exception("申请用户异常，请重新处理", 404);
        }
        if ($refund_order_sn == '') {
            throw new \think\Exception("售后订单不存在", 404);
        }
        if ($need_pay <= 0) {
            throw new \think\Exception("审核退款金额小于0 无需执行退款操作", 404);
        }
        // 写入用户页退还记录
        $back_money_data = [];
        $back_money_data['sub_order_sn'] = $refund_order_sn; // 关联订单编号
        $back_money_data['create_user_sn'] = $user_sn; // 下单人编号
        $back_money_data['user_sn'] = $user_sn;
        $back_money_data['achievement_price'] = 0; // 业绩金额
        $back_money_data['user_level'] = 0; // 代理等级
        $back_money_data['agent_bili'] = 0; // 代理佣金比例
        $back_money_data['act'] = 9; // 类型 用户退款
        $back_money_data['is_finance'] = 1; // 是否结算 代理佣金按月出账
        $back_money_data['finance_time'] = date('Y-m-d H:i:s'); // 结算时间
        $back_money_data['money'] = $need_pay; // 代理佣金
        $back_money_data['content'] = '用户退款返还佣金'.$need_pay.'元';
        $userModel->where([['user_sn','=',$user_sn]])->inc('back_money', (float)$need_pay)->update();
        $backMoneyModel->create($back_money_data); // 写入代理返佣记录
        $order_data = [];
        $order_data['refund_price'] = $need_pay;
        $order_data['refund_code'] = $refundOrderModel->getCodeNo(date('YmdHis'), 15, 1, 'refund_code');
        $order_data['finish_time'] = date('Y-m-d H:i:s');
        // 开始执行 相关操作
        $order_data['status'] = 1.3; // 退款完成
        if ($data['type'] == 2) {
            $order_data['status'] = 2.5; // 退货完成
        }
        $refund_order_res = $refundOrderModel->where([['refund_order_sn','=',$refund_order_sn]])->save($order_data);
        // 写入余额财务记录


        // $finance_datax = [];
        // $finance_datax['relation_num'] = $refund_order_sn;
        // $finance_datax['relation_user_num'] = $user_sn;
        // $finance_datax['entry'] = 1;
        // $finance_datax['money'] = $need_pay;
        // $finance_datax['content'] = '退还到余额，平台收入';
        // $finance_datax['pay_order_sn'] = isset($data['pay_order_sn'])?$data['pay_order_sn']:'';
        // $finance_datax['pay_type'] = 3;
        // $finance_datax['act'] = 4;
        // $financeServices->syncFinance($finance_datax);

        $finance_data = [];
        $finance_data['relation_num'] = $refund_order_sn;
        $finance_data['relation_user_num'] = $user_sn;
        $finance_data['entry'] = 2;
        $finance_data['money'] = $need_pay;
        $finance_data['content'] = '用户余额退款，平台支出';
        $finance_data['pay_order_sn'] = isset($data['pay_order_sn'])?$data['pay_order_sn']:'';
        $finance_data['pay_type'] = 3;
        $finance_data['act'] = 4;
        $financeServices->syncFinance($finance_data);
        $orderServices->syncRefundResult($refund_order_sn);
        return true;
    }
    /**
     * @xk 计算本月团队扣除业绩最多一条线的总业绩
     *
     * @method getTeamAchievementPrice
     * @param  [type]                  $user_sn                   [description]
     * @param  [type]                  $condition                 [description]
     * @return [type]                  [description]
     * @Time   2021-11-10
     * @City   青岛
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     */
    public static function getTeamAchievementPrice($user_sn, $condition)
    {
        $userModel = new UserModel();
        $userAchievementModel = new UserAchievementModel();
        $max_achievement_price = 0.00; // 伞下业绩最多的业绩
        $team_achievement_price = 0.00;
        $all_achievement_price = 0.00;
        // 开始 各种业绩计算
        $all_achievement_price = $userAchievementModel
                                ->where($condition)
                                ->where([['user_sn','=',$user_sn]])
                                ->sum('achievement_price');
        // 获取本人v1团队
        $v1_list = $userModel
                  ->where([['l_user_sn','=',$user_sn]])
                  ->field('`user_sn`')
                  ->select()
                  ->toArray();
        $team_arr = [];
        foreach ($v1_list as $k => $val) {
            // 开始获取团队的总业绩
            $team_arr[] = $userAchievementModel
                  ->where($condition)
                  ->where([['user_sn','=',$val['user_sn']]])
                  ->sum('achievement_price');
        }
        if ($team_arr) {
            $max_achievement_price = max($team_arr);
        }
        $team_achievement_price = $all_achievement_price - $max_achievement_price;
        // $team_achievement_price = $all_achievement_price;
        // 最小为0
        return $team_achievement_price>0 ? $team_achievement_price : 0.00;
    }
    /**
     * @xk 开始校验每月分红
     *
     * @method syncBonus
     * @return [type]     [description]
     * @Time   2021-11-10
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public static function syncBonusUser()
    {
        $userModel = new UserModel();
        $userAchievementModel = new UserAchievementModel();
        $bonusUserModel = new BonusUserModel();
        $userUpLogModel = new UserUpLogModel();
        $taskService = new Task();
        $user_list = $userModel
                  ->where([['level','=',5]])
                  ->field('`user_sn`,`user_name`,`level`')
                  ->select()
                  ->toArray();
        if ($user_list) {
            foreach ($user_list as $key => $value) {
                $condition = [];
                $now_month = getLastDate('Y-m', 2, 1);
                $condition[] = ['create_time','like',$now_month.'%']; // 查询上月全部业绩
                // 查询当前用户最近一次升级 时间
                $user_up_create = $userUpLogModel
                                  ->where([['user_sn','=',$value['user_sn'],['level','=',5]]])
                                  ->field('`create_time`')
                                  ->order('create_time desc')
                                  ->limit(1)
                                  ->select()
                                  ->toArray();
                if($user_up_create){
                  $condition[] = ['create_time','>',$user_up_create['0']['create_time']];
                }
                // 当月总业绩
                $all_achievement_price = $userAchievementModel
                ->where($condition)
                ->where([['user_sn','=',$value['user_sn']]])
                ->sum('achievement_price');
                $month = getLastDate('Ym', 2, 1);
                $count = $bonusUserModel->where([['user_sn','=',$value['user_sn']],['month','=',$month]])->count();
                $bonus_data = [];
                $bonus_data['user_sn'] = $value['user_sn'];
                $bonus_data['month'] = $month;
                $bonus_data['user_name'] = $value['user_name'];
                $bonus_data['level'] = $value['level'];
                $bonus_data['all_achievement_price'] = $all_achievement_price;
                if ($count <= 0) {
                    $bonusUserModel->create($bonus_data); // 写入对应的会员
                } else {
                    // 如果已经存在当前会员 则 更新会员数据
                    $bonusUserModel->where([['user_sn','=',$value['user_sn']],['month','=',$month]])->save($bonus_data);
                }
            }
        }
        // 循环完毕 可以开始执行第二个步骤计划 执行返利
        $msgData = ['time' => date('YmdHis'), 'msgId' => '', 'jobAction' => 'syncBonusBackMoney'];
        $delay = 10;
        $taskService->put($msgData, $delay);
    }
    /**
     * @xk 开始执行每月分红
     *
     * @method syncBonusBackMoney
     * @return [type]             [description]
     * @Time   2021-11-10
     * @City   青岛
     * @Author xkyinzhe           <zhonghuaxinxing@sina.cn>
     */
    public static function syncBonusBackMoney()
    {
        $backMoneyModel = new BackMoneyModel(); // 返佣列表
        $bonusRuleModel = new BonusRuleModel(); // 分红规则
        $bonusUserModel = new BonusUserModel(); // 铂金会员表
        $userAchievementModel = new UserAchievementModel(); // 会员业绩榜单
        $condition = [];
        $now_month = getLastDate('Y-m', 2, 1);
        $condition[] = ['create_time','like',$now_month.'%']; // 查询上月全部业绩
        // 获取平台总业绩
        $all_list = $userAchievementModel->where($condition)->group('sub_order_sn')->column('achievement_price');
        $all_price = array_sum($all_list); // 平台总业绩
        // 获取分红规则
        $bonus_list = $bonusRuleModel->field('*')->select();
        if ($bonus_list) {
            foreach ($bonus_list as $key => $value) {
                $all = $value['all'];
                // 存在分红规则
                $condition = [];
                $condition[]= ['month','=',getLastDate('Ym', 2, 1)]; // 分发当月
                $condition[] = ['all_achievement_price','>=',$all]; // 团队业绩
          // 满足条件的总业绩
          $sum_price = $bonusUserModel
                        ->where($condition)
                        ->sum('all_achievement_price');
          $user_list = $bonusUserModel
                       ->where($condition)
                       ->field('*')
                       ->select()
                       ->toArray();
                if ($user_list) {
                    foreach ($user_list as $k => $val) {
                        // 开始计算分红金额
                        $back_money = $val['all_achievement_price']/$sum_price*$all_price*$value['bonus_bili']; // 分
                        $back_money_data = [];
                        $back_money_data = [];
                        $back_money_data['sub_order_sn'] = date('YmdHis'); // 关联订单编号
                        $back_money_data['create_user_sn'] = 0000000000001; // 下单人编号
                        $back_money_data['user_sn'] = $val['user_sn'];
                        $back_money_data['achievement_price'] = $val['all_achievement_price']; // 团队总业绩
                        $back_money_data['user_level'] = $val['level']; // 会员等级
                        $back_money_data['bonus_level'] = $value['bonus_rule_id']; // 分红等级
                        $back_money_data['bonus_price'] = $all_price; // 分红等级
                        $back_money_data['act'] = 4; // 类型 代理佣金
                        $back_money_data['is_finance'] = 0; // 是否结算 代理佣金按月出账
                        $back_money_data['money'] = $back_money; // 代理佣金
                        $back_money_data['content'] = '用户参与分红'.$back_money.'元';
                        if ($back_money >= 0) {
                            $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                        }
                    }
                }
            }
        }
    }
    /**
     * @xk 执行后台出账
     * @method  syncPushBackMoney
     * @param   string $back_money_ids  [description]
     * @return  [type] [description]
     * @Version V5.0
     * @Time    2021-11-11
     * @City    青岛
     * @Author  xkyinzhe <zhonghuaxinxing@sina.cn>
     */
    public static function syncPushBackMoney($back_money_ids = '')
    {
        if (!$back_money_ids) {
            throw new \think\Exception("请选择需要出账的数据", 404);
        }
        $backMoneyModel = new BackMoneyModel(); // 出账的数据
        $userModel = new UserModel(); // 会员数据
        $subOrderModel = new SubOrderModel(); // 子订单数据
        $avgBackMoneyModel = new AvgBackMoneyModel(); // 未结算平级奖励
        $sendMsg = new SendMsg();
        $back_money_list = $backMoneyModel
        ->where([['back_money_id','in',$back_money_ids]])
        ->field('`back_money_id`,`user_sn`,`sub_order_sn`,`act`,`money`,`is_finance`')
        ->select()
        ->toArray();
        if ($back_money_list) {
            foreach ($back_money_list as $key => $value) {
                if ($value['is_finance'] != 0) {
                    continue;
                }
                // 第一步
                $user_condition = [];
                $user_condition[] = ['user_sn','=',$value['user_sn']];
                // 开始增加用户佣金
                $user_res = $userModel->where($user_condition)->inc('back_money', (float)$value['money'])->update();
                $all_user_res = $userModel->where($user_condition)->inc('all_back_money', (float)$value['money'])->update();
                // 开始修改结算状态
                $finance_data = [];
                $finance_data['is_finance'] = 1;
                $finance_data['finance_time'] = date('Y-m-d H:i:s');
                $back_res = $backMoneyModel->find($value['back_money_id'])->save($finance_data); // 结算状态更新

                // $create_data = [];
                // $create_data['money'] = (float)$value['money'];
                // $create_data['time'] = $finance_data['finance_time'];
                // $contentx = '尊敬的用户，您佣金已经成功发放！';
                // $sendMsg->sendPushMsg($value['user_sn'], '佣金到账通知', $contentx, 5, $create_data);

                if ($value['act'] == 2 || $value['act'] == 3) {
                    // 判断是否存在 未计算代理佣金 或平级奖佣金 如果不存在 则修正订单状态为已出账
                    $back_count = $backMoneyModel->where([['sub_order_sn','=',$value['sub_order_sn']],['is_finance','=',0]])->count();
                    $wait_back_count = $avgBackMoneyModel->where([['sub_order_sn','=',$value['sub_order_sn']],['is_finance','=',0]])->count();
                    if ($back_count <= 0 && $wait_back_count <= 0) {
                        // 没有未出账佣金 没有等待结算的平级奖励 订单完成全部出账
                        $sub_res = $subOrderModel->where([['sub_order_sn','=',$value['sub_order_sn']]])->find()->save(['is_check'=>1,'check_time'=>date('Y-m-d H:i:s')]);
                    }
                }
            }
        }
    }
    /**
     * @xk 余额转增执行
     *
     * @method syncBalanceFinance
     * @param  [type]             $id_str                    [description]
     * @return [type]             [description]
     * @Time   2021-11-12
     * @City   青岛
     * @Author xkyinzhe           <zhonghuaxinxing@sina.cn>
     */
    public static function syncBalanceFinance($id_str='', $status=1, $content = '')
    {
        $moneyChanageModel = new MoneyChanageModel();
        $userModel = new UserModel();
        $backMoneyModel = new BackMoneyModel();
        $list = $moneyChanageModel
              ->where([['money_chanage_id','in',$id_str]])
              ->field('`money_chanage_id`,`money`,`push_user_sn`,`user_sn`,`status`')
              ->select()
              ->toArray();
        if ($list) {
            foreach ($list as $key => $value) {
                if ($value['status'] != 0) {
                    continue;
                }
                switch ($status) {
                  case '1':
                    // 同意转增
                    $back_money_data = [];
                    $back_money_data['sub_order_sn'] = date('YmdHis'); // 关联订单编号
                    $back_money_data['create_user_sn'] = $value['push_user_sn']; // 下单人编号
                    $back_money_data['user_sn'] = $value['user_sn'];
                    $back_money_data['achievement_price'] = 0; // 业绩金额
                    $back_money_data['user_level'] = 0; // 代理等级
                    $back_money_data['agent_bili'] = 0; // 代理佣金比例
                    $back_money_data['act'] = 6; // 类型 余额转入
                    $back_money_data['is_finance'] = 1; // 是否结算 代理佣金按月出账
                    $back_money_data['finance_time'] = date('Y-m-d H:i:s'); // 结算时间
                    $back_money_data['money'] = $value['money']; // 代理佣金
                    $back_money_data['content'] = '后台审核通过用户'.$value['push_user_sn'].'给用户'.$value['user_sn'].'的余额转增';
                    $push_back_money_data = [];
                    $push_back_money_data['sub_order_sn'] = date('YmdHis'); // 关联订单编号
                    $push_back_money_data['create_user_sn'] = $value['push_user_sn']; // 下单人编号
                    $push_back_money_data['user_sn'] = $value['push_user_sn'];
                    $push_back_money_data['achievement_price'] = 0; // 业绩金额
                    $push_back_money_data['user_level'] = 0; // 代理等级
                    $push_back_money_data['agent_bili'] = 0; // 代理佣金比例
                    $push_back_money_data['act'] = 5; // 类型 余额转出
                    $push_back_money_data['is_finance'] = 1; // 是否结算 代理佣金按月出账
                    $push_back_money_data['finance_time'] = date('Y-m-d H:i:s'); // 结算时间
                    $push_back_money_data['money'] = $value['money']; // 代理佣金
                    $push_back_money_data['content'] = '后台审核通过用户'.$value['push_user_sn'].'给用户'.$value['user_sn'].'的余额转增';
                    $push_user_res = $userModel->where([['user_sn','=',$value['push_user_sn']]])->dec('frozen_money', (float)$value['money'])->update();
                    $back_res = $backMoneyModel->create($back_money_data); // 写入代理返佣记录
                    $push_back_res = $backMoneyModel->create($push_back_money_data); //入代理返佣记录
                    $user_res = $userModel->where([['user_sn','=',$value['user_sn']]])->inc('back_money', (float)$value['money'])->update();
                    $all_user_res = $userModel->where([['user_sn','=',$value['user_sn']]])->inc('all_back_money', (float)$value['money'])->update();
                    $moneyChanageModel->find($value['money_chanage_id'])->save(['status'=>1,'finance_time'=>date('Y-m-d H:i:s')]);
                    break;
                  case '2':
                    // 退还转出余额
                    $push_user_res = $userModel->where([['user_sn','=',$value['push_user_sn']]])->dec('frozen_money', (float)$value['money'])->update();
                    $user_res = $userModel->where([['user_sn','=',$value['push_user_sn']]])->inc('back_money', (float)$value['money'])->update();
                    $moneyChanageModel->find($value['money_chanage_id'])->save(['status'=>2,'finance_time'=>date('Y-m-d H:i:s'),'content'=>$content]);
                    break;
                }
            }
        }
    }
    /**
     * @xk 执行提现驳回
     *
     * @method syncBackWithDrawal
     * @param  [type]             $id_str                    [description]
     * @return [type]             [description]
     * @Time   2021-12-06
     * @City   青岛
     * @Author xkyinzhe           <zhonghuaxinxing@sina.cn>
     */
    public static function syncBackWithDrawal($id_str, $status)
    {
        $withDrawalModel = new WithDrawalModel();
        $userModel = new UserModel();
        $sendMsg = new SendMsg();
        // 如果提现失败  则增加用户月
        $with_list = $withDrawalModel
                  ->alias('w')
                  ->leftJoin('user u', 'u.user_sn = w.user_sn')
                  ->where([['w.with_drawal_id','in',$id_str]])
                  ->field('w.`user_sn`,w.`status`,w.`money`,u.`user_name`')
                  ->select()
                  ->toArray();
        if ($with_list) {
            foreach ($with_list as $key => $value) {
                $user_sn = $value['user_sn'];
                $money = $value['money'];
                switch ($value['status']) {
                  case '2':
                    $create_data = [];
                    $create_data['user_name'] = $value['user_name'];
                    $create_data['money'] = (float)$money;
                    $contentx = '尊敬的用户，您提交的提现申请被管理员操作驳回，相关佣金已经原路退还。';
                    break;
                  case '4':
                    $create_data = [];
                    $create_data['user_name'] = $value['user_name'];
                    $create_data['money'] = (float)$money;
                    $contentx = '尊敬的用户，您提交的提现申请打款过程中出现异常，被操作驳回，相关佣金已经原路退还。';
                    break;
                }
              $userModel->where([['user_sn', '=', $user_sn]])->inc('back_money', (float)$money)->update();
              $userModel->where([['user_sn', '=', $user_sn]])->dec('frozen_money', (float)$money)->update();
              // $sendMsg->sendPushMsg($value['user_sn'], '提现审核通知', $contentx, 6, $create_data);
            }
        }
    }
    /**
     * @xk 提现成功处理
     *
     * @method syncPushSuccess
     * @param  [type]          $withdrawal_sn             [description]
     * @return [type]          [description]
     * @Time   2021-12-06
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public static function syncPushSuccess($withdrawal_sn)
    {
        $withDrawalModel = new WithDrawalModel();
        $financeServices = new FinanceServices(); // 财务记录
        $sendMsg = new SendMsg();
        $with_info = $withDrawalModel
                  ->alias('wtd')
                  ->leftJoin('user u', 'u.user_sn = wtd.user_sn')
                  ->where([['wtd.withdrawal_sn','=',$withdrawal_sn]])
                  ->field('wtd.`withdrawal_sn`,wtd.`user_sn`,wtd.`status`,wtd.`money`,u.`user_name`')
                  ->find();
        // 写入余额财务记录
        $finance_data = [];
        $finance_data['relation_num'] = $withdrawal_sn;
        $finance_data['relation_user_num'] = $with_info['user_sn'];
        $finance_data['entry'] = 2;
        $finance_data['money'] = $with_info['money'];
        $finance_data['content'] = '用户提现成功，平台支出';
        $finance_data['pay_type'] = 3;
        $finance_data['act'] = 3;
        $financeServices->syncFinance($finance_data);
        // $create_data = [];
        // $create_data['user_name'] = $with_info['user_name'];
        // $create_data['money'] = (float)$with_info['money'];
        // $contentx = '尊敬的用户，您提交的提现申请已经通过，相关佣金已经发放至提现银行卡！';
        // $sendMsg->sendPushMsg($with_info['user_sn'], '提现审核通知', $contentx, 6, $create_data);
    }
    /**
     * @xk 同步升级数据
     * @method                                      syncCheckUp
     * @param                                       string $create_user_sn  [description]
     * @param                                       string $push_user_sn  [description]
     * @param                                       string $user_sn  [description]
     * @param                                       int $level  [description]
     * @param                                       string $act  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-03-17Tfalse17:false30:false43+080
     */
    public static function syncCheckUp($create_user_sn = '', $do_user_sn='', $push_user_sn='', $user_sn='', $level=1, $act='inc',$search_arr=[])
    {
        $userModel = new UserModel();
        // 查询推介人数据
        $push_user_info = $userModel
                        ->where([['user_sn','=',$push_user_sn]])
                        ->field('`level`,`level_1_count`,`level_2_count`,`level_3_count`,`level_4_count`,`level_5_count`,`is_push_now`')
                        ->find();
        $push_user_info = $push_user_info ? $push_user_info->toArray() : [];
        // 执行人数据
        $user_info_ref = $userModel
                      ->where([['user_sn','=',$user_sn]])
                      ->field('`user_sn`,`l_user_sn`,`level`,`level_1_count`,`level_2_count`,`level_3_count`,`level_4_count`,`level_5_count`')
                      ->find();
        $user_info = $user_info_ref ? $user_info_ref->toArray() : [];
        // 方法分组 inc 升级 desc降级 chanageUp 绑入 chanageOut 退出
        $is_owner = $create_user_sn == $push_user_sn ? 1 : 0;
        $search_keywords = 'level_'.$level.'_count';
        $level_count = $push_user_info ? $push_user_info['level_'.$level.'_count'] : 0;
        $check_now_time = checkNowTime(); // 检测是否处在脚本执行过程中
        switch ($act) {
        case 'inc':
          switch ($is_owner) {
            case '1':
              // 如果是同一个人 判断当前等级数量是否小于等于0 如果小于等于0 则说明可以给上级累计 同时给上上级累计
              if ($level_count <= 0) {
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Inc($search_keywords, 1)->update();
                  $res = $userModel->where([['user_sn','=',$push_user_sn]])->save(['is_push_now'=>1]); // 提示 给上级进行过当前本人等级的累计
                  // 记录 给上级增加了一个当前等级的
                  createLog("searchCheck/",$level.'======'.$create_user_sn."=====[+1]====".$user_sn);
                  if ($user_info['l_user_sn'] > 0) {
                      // 上级等级增加 同时判断是否需要族谱增加
                      self::syncCheckUp($create_user_sn, $do_user_sn, $user_sn, $user_info['l_user_sn'], $level, $act,$search_arr);
                  }else{
                    if($check_now_time == 1){
                      self::doCheckUp($do_user_sn);
                    }
                  }
              }else{
                if($check_now_time == 1){
                  self::doCheckUp($do_user_sn);
                }
              }
              break;
            case '0':
              // 当前等级数量为1 同时 等级 不等于当前等级 是为 可以给上级累加
              // 当前等级数量为1 同时 等级是当前等级 同时 本人没有向上级进行累加 则可以给上级进行累加
              if(($level_count==1 && $push_user_info['level'] != $level) || ($level_count==1 && $push_user_info['level'] == $level && $push_user_info['is_push_now'] == 0)){
                $res = $userModel->where([['user_sn','=',$user_sn]])->Inc($search_keywords, 1)->update();
                // 记录 给上级增加了一个当前等级的
                createLog("searchCheck/",$level.'==='.$push_user_info['is_push_now'].'==='.$create_user_sn."=====[+1]====".$user_sn);
                if ($user_info['l_user_sn'] > 0) {
                    self::syncCheckUp($create_user_sn, $do_user_sn, $user_sn, $user_info['l_user_sn'], $level, $act,$search_arr);
                }else{
                  if($check_now_time == 1){
                    self::doCheckUp($do_user_sn);
                  }
                }
              }else{
                if($check_now_time == 1){
                  self::doCheckUp($do_user_sn);
                }
              }
              break;
          }
          break;
        case 'desc':
          // 分组 创建人和贡献人关系
          // 如果是同一个人 判断当前等级数量是否小于等于0 如果小于等于0 并当前等级不是目标等级 则说明需要取消上级累计 同时给上上级取消累计
          switch ($is_owner) {
            case 1:
              // 如果是同一个人 判断当前等级数量是否小于等于0 如果小于等于0 则说明可以给上级累计 同时给上上级累计
              if ($level_count <= 0) {
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Dec($search_keywords, 1)->update();
                  // 记录 给上级增加了一个当前等级的
                  createLog("searchCheck/",$level.'======'.$create_user_sn."=====[-1]====".$user_sn);
                  if ($user_info['l_user_sn'] > 0) {
                      // 上级等级增加 同时判断是否需要族谱增加
                      self::syncCheckUp($create_user_sn, $do_user_sn, $user_sn, $user_info['l_user_sn'], $level, $act);
                  }
              }
              break;
            case 0:
              // 如果不是同一个人 那么判断当前等级数量是否等于1 如果等于1 则可以给上级累计 同时给上上级累计
              if ($level_count <= 0 && $push_user_info['level'] != $level) {
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Dec($search_keywords, 1)->update();
                  // 记录 给上级增加了一个当前等级的
                  createLog("searchCheck/",$level.'======'.$create_user_sn."=====[-1]====".$user_sn);
                  if ($user_info['l_user_sn'] > 0) {
                      // 上级等级增加 同时判断是否需要族谱增加
                      self::syncCheckUp($create_user_sn, $do_user_sn, $user_sn, $user_info['l_user_sn'], $level, $act);
                  }
              }
              break;
          }
          break;
        case 'chanageUp':
          // 查询推介人全部信息
          // 查询各个等级的情况 开始判断上级是否增加 如果本人是本人则判断小于等于
          // 更换等级过程中增加
          switch ($is_owner) {
            case 1:
              // 此处 推介人和触发人是同一个人
              if ($level == 1 || $push_user_info['level_1_count'] > 0) {
                createLog('chanageLUserSn/',$create_user_sn.'=【1】==【+1】==='.$user_sn); // 换绑上下级 同步数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Inc('level_1_count', 1)->update();
                  $search_arr[] = 1;
              }
              if ($level == 2 || $push_user_info['level_2_count'] > 0) {
                  // 如果存在高一个等级的数据
                  createLog('chanageLUserSn/',$create_user_sn.'=【2】==【+1】==='.$user_sn); // 换绑上下级 同步数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Inc('level_2_count', 1)->update();
                  $search_arr[] = 2;
              }
              if ($level == 3 || $push_user_info['level_3_count'] > 0) {
                  // 如果存在高一个等级的数据
                  createLog('chanageLUserSn/',$create_user_sn.'=【3】==【+1】==='.$user_sn); // 换绑上下级 同步数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Inc('level_3_count', 1)->update();
                  $search_arr[] = 3;
              }
              if ($level == 4 || $push_user_info['level_4_count'] > 0) {
                  // 如果存在高一个等级的数据
                  createLog('chanageLUserSn/',$create_user_sn.'=【4】==【+1】==='.$user_sn); // 换绑上下级 同步数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Inc('level_4_count', 1)->update();
                  $search_arr[] = 4;
              }
              if ($level == 5 || $push_user_info['level_5_count'] > 0) {
                  // 如果存在高一个等级的数据
                  createLog('chanageLUserSn/',$create_user_sn.'=【5】==【+1】==='.$user_sn); // 换绑上下级 同步数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Inc('level_5_count', 1)->update();
                  $search_arr[] = 5;
              }
              break;
            case 0:
              // 此处 推介人和触发人不是同一个人
              if ($push_user_info['level_1_count'] == 1 && $push_user_info['level'] != 1 && in_array(1,$search_arr)) {
                  // 说明是刚刚增加的那个人
                  createLog('chanageLUserSn/',$create_user_sn.'=【1】==【+1】==='.$user_sn); // 换绑上下级 同步数据
                $res = $userModel->where([['user_sn','=',$user_sn]])->Inc('level_1_count', 1)->update(); // 触发升级
              }
              if ($push_user_info['level_2_count'] == 1  && $push_user_info['level'] != 2 && in_array(2,$search_arr)) {
                  // 如果存在高一个等级的数据
                  createLog('chanageLUserSn/',$create_user_sn.'=【2】==【+1】==='.$user_sn); // 换绑上下级 同步数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Inc('level_2_count', 1)->update();
              }
              if ($push_user_info['level_3_count'] == 1  && $push_user_info['level'] != 3 && in_array(3,$search_arr)) {
                  // 如果存在高一个等级的数据
                  createLog('chanageLUserSn/',$create_user_sn.'=【3】==【+1】==='.$user_sn); // 换绑上下级 同步数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Inc('level_3_count', 1)->update();
              }
              if ($push_user_info['level_4_count'] == 1  && $push_user_info['level'] != 4 && in_array(4,$search_arr)) {
                  // 如果存在高一个等级的数据
                  createLog('chanageLUserSn/',$create_user_sn.'=【4】==【+1】==='.$user_sn); // 换绑上下级 同步数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Inc('level_4_count', 1)->update();
              }
              if ($push_user_info['level_5_count'] == 1  && $push_user_info['level'] != 5 && in_array(5,$search_arr)) {
                  // 如果存在高一个等级的数据
                  createLog('chanageLUserSn/',$create_user_sn.'=【5】==【+1】==='.$user_sn); // 换绑上下级 同步数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Inc('level_5_count', 1)->update();
              }
              break;
          }
          if ($user_info['l_user_sn'] > 0) {
              // 上级等级增加 同时判断是否需要族谱增加
              self::syncCheckUp($create_user_sn, $do_user_sn, $user_sn, $user_info['l_user_sn'], $level, $act,$search_arr);
          }else{
            self::doCheckUp($do_user_sn);
          }
          break;
        case 'chanageOut':
          // 查询推介人全部信息
          // 查询各个等级的情况 开始判断上级是否增加 如果本人是本人则判断小于等于
          switch ($is_owner) {
            case 1:
              // 此处 推介人和触发人是同一个人
              if ($level == 1 || $push_user_info['level_1_count'] > 0) {
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Dec('level_1_count', 1)->update();
                  $search_arr[] = 1;
                  createLog('chanageLUserSn/',$create_user_sn.'=【1】==【-1】==='.$user_sn); // 换绑上下级 同步数据
              }
              if ($level == 2 || $push_user_info['level_2_count'] > 0) {
                  // 如果存在高一个等级的数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Dec('level_2_count', 1)->update();
                  createLog('chanageLUserSn/',$create_user_sn.'=【2】==【-1】==='.$user_sn); // 换绑上下级 同步数据
                  $search_arr[] = 2;
              }
              if ($level == 3 || $push_user_info['level_3_count'] > 0) {
                  // 如果存在高一个等级的数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Dec('level_3_count', 1)->update();
                  createLog('chanageLUserSn/',$create_user_sn.'=【3】==【-1】==='.$user_sn); // 换绑上下级 同步数据
                  $search_arr[] = 3;
              }
              if ($level == 4 || $push_user_info['level_4_count'] > 0) {
                  // 如果存在高一个等级的数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Dec('level_4_count', 1)->update();
                  createLog('chanageLUserSn/',$create_user_sn.'=【4】==【-1】==='.$user_sn); // 换绑上下级 同步数据
                  $search_arr[] = 4;
              }
              if ($level == 5 || $push_user_info['level_5_count'] > 0) {
                  // 如果存在高一个等级的数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Dec('level_5_count', 1)->update();
                  createLog('chanageLUserSn/',$create_user_sn.'=【5】==【-1】==='.$user_sn); // 换绑上下级 同步数据
                  $search_arr[] = 5;
              }
              break;
            case 0:
              // 此处 推介人和触发人不是同一个人
              if ($push_user_info['level_1_count'] == 0 && $push_user_info['level'] != 1 && in_array(1,$search_arr)) {
                  // 说明是刚刚增加的那个人
                  createLog('chanageLUserSn/',$create_user_sn.'=【1】==【-1】==='.$user_sn); // 换绑上下级 同步数据
                $res = $userModel->where([['user_sn','=',$user_sn]])->Dec('level_1_count', 1)->update(); // 触发升级
              }
              if ($push_user_info['level_2_count'] == 0 && $push_user_info['level'] != 2 && in_array(2,$search_arr)) {
                  // 如果存在高一个等级的数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Dec('level_2_count', 1)->update();
                  createLog('chanageLUserSn/',$create_user_sn.'=【2】==【-1】==='.$user_sn); // 换绑上下级 同步数据
              }
              if ($push_user_info['level_3_count'] == 0 && $push_user_info['level'] != 3 && in_array(3,$search_arr)) {
                  // 如果存在高一个等级的数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Dec('level_3_count', 1)->update();
                  createLog('chanageLUserSn/',$create_user_sn.'=【3】==【-1】==='.$user_sn); // 换绑上下级 同步数据
              }
              if ($push_user_info['level_4_count'] == 0 && $push_user_info['level'] != 4 && in_array(4,$search_arr)) {
                  // 如果存在高一个等级的数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Dec('level_4_count', 1)->update();
                  createLog('chanageLUserSn/',$create_user_sn.'=【4】==【-1】==='.$user_sn); // 换绑上下级 同步数据
              }
              if ($push_user_info['level_5_count'] == 0 && $push_user_info['level'] != 5 && in_array(5,$search_arr)) {
                  // 如果存在高一个等级的数据
                  $res = $userModel->where([['user_sn','=',$user_sn]])->Dec('level_5_count', 1)->update();
                  createLog('chanageLUserSn/',$create_user_sn.'=【5】==【-1】==='.$user_sn); // 换绑上下级 同步数据
              }
              break;
          }
          if(!empty($user_info['l_user_sn'])){
            if ($user_info['l_user_sn'] > 0) {
              // 上级等级增加 同时判断是否需要族谱增加
              self::syncCheckUp($create_user_sn, $do_user_sn, $user_sn, $user_info['l_user_sn'], $level, $act, $search_arr);
            }  
          }
          
          break;
      }
    }
    /**
     * @xk 执行会员数据统计
     * @method                                 syncUpdateCheck
     * @return                                 [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                        <zhonghuaxinxing@sina.cn>
     * @City：                                  青岛
     * @Time：2022-03-18Tfalse10:false18:00+080
     */
    public static function syncUpdateCheck()
    {
        $userModel = new UserModel();
        $path = 'syncUpdateCheck/';
        // 查询数据库中的数据
        $count = $userModel->where([['l_user_sn','>',0],['is_count','=',0]])->count();
        $page = 1;
        $limit = 3000;
        $j = 1;
        $list = [];
        $list = $userModel
                ->where([['l_user_sn','>',0],['is_count','=',0]])
                ->field('`user_sn`,`l_user_sn`,`level`,`user_id`')
                ->limit($limit)
                ->select()
                ->toArray();
        if ($list) {
            $content = '';
            foreach ($list as $key => $value) {
                $taskService = new Task();
                // 循环完毕 可以开始执行第二个步骤计划 执行返利
                $msgData = ['time' => date('YmdHis'), 'msgId' => $value['user_sn'],'l_user_sn'=>$value['l_user_sn'],'level'=>$value['level'],'count'=>$j, 'jobAction' => 'syncDoCheckUp'];
                $delay = 60;
                $taskService->put($msgData, $delay);
                $content .=  $value['user_sn'].'-';
                $content .=$j."[完成]";
                $userModel->find($value['user_id'])->save(['is_count'=>1]);
                $j++;
            }
            createLog($path, $content);
        }
    }
}
